<template>
  <div class="app">
    <div class="header">
      <h1>元数据编制工具</h1>
      <div class="layout-controls">
        <button 
          @click="layout = 'horizontal'" 
          :class="['layout-button', layout === 'horizontal' ? 'active' : '']"
        >
          水平布局
        </button>
        <button 
          @click="layout = 'vertical'" 
          :class="['layout-button', layout === 'vertical' ? 'active' : '']"
        >
          垂直布局
        </button>
      </div>
    </div>
    
    <!-- 主内容区域 -->
    <div :class="['main-content', layout]">
      <div class="editor-section">
        <TemplateEditor 
          @update-preview="handlePreviewUpdate"
          @save-template="handleSaveTemplate"
          @load-template="handleLoadTemplate"
          :initial-template="currentTemplate"
          :available-templates="availableTemplates"
        />
      </div>
      
      <div class="preview-section">
        <PreviewPanel 
          :yaml-content="yamlContent"
          :xml-content="xmlContent"
          :proto-content="protoContent"
          :template-name="currentTemplate?.name || 'template'"
        />
      </div>
    </div>
    
    <!-- 模板列表垂直布局部分 -->
    <div class="template-list-section">
      <TemplateList 
        :templates="templates"
        @load="handleLoadTemplate"
        @delete="handleDeleteTemplate"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import TemplateEditor from './components/TemplateEditor.vue';
import PreviewPanel from './components/PreviewPanel.vue';
import TemplateList from './components/TemplateList.vue';
import { getTemplates, saveTemplate, deleteTemplate, type Template } from './utils/storage';
import { toYaml, toXml } from './utils/format';
import { generateProto } from './utils/proto-generator';

// 状态管理
const templates = ref<Template[]>([]);
const yamlContent = ref<string>('');
const xmlContent = ref<string>('');
const protoContent = ref<string>('');
const currentTemplate = ref<Template | null>(null);
const layout = ref<'vertical' | 'horizontal'>('horizontal');


// 初始化
onMounted(() => {
  templates.value = getTemplates();
});

// 可用模板（排除当前正在编辑的模板）
const availableTemplates = computed(() => {
  return templates.value.filter(tpl => 
    !currentTemplate.value || tpl.id !== currentTemplate.value.id
  );
});

// 处理预览更新
const handlePreviewUpdate = (templateData: Template | null) => {
  // 传递当前模板列表而不是从存储中获取
  yamlContent.value = toYaml(templateData, templates.value);
  xmlContent.value = toXml(templateData, templates.value);
  protoContent.value = generateProto(templateData, templates.value);
};

// 保存模板
const hasCycle = (template: Template | null, allTemplates: Template[], visited: Set<string> = new Set()): boolean => {
  if (!template || !template.id) return false;
  if (visited.has(template.id)) return true;
  visited.add(template.id);

  for (const field of template.fields || []) {
    if (field.type === 'template' && field.templateId && field.templateId.trim() !== '') {
      const nested = allTemplates.find(t => t.id === field.templateId);
      if (nested && hasCycle(nested, allTemplates, new Set(visited))) {
        return true;
      }
    }
  }
  return false;
};

const handleSaveTemplate = (template: Template) => {
  // 检查循环引用
  if (hasCycle(template, templates.value)) {
    alert('模板存在循环引用，请修改后再保存');
    return;
  }

  saveTemplate(template);
  templates.value = getTemplates();
};

// 加载模板
const handleLoadTemplate = (template: Template) => {
  currentTemplate.value = template;
  handlePreviewUpdate(template);
};

// 删除模板
const handleDeleteTemplate = (id: string) => {
  deleteTemplate(id);
  templates.value = getTemplates();
  if (currentTemplate.value?.id === id) {
    currentTemplate.value = null;
    yamlContent.value = '';
    xmlContent.value = '';
    protoContent.value = '';
  }
};
</script>

<style scoped>
.app {
  animation: fadeIn 0.5s ease-in;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
}

.layout-controls {
  display: flex;
  gap: 8px;
}

.layout-button {
  padding: 8px 16px;
  background-color: var(--bg-secondary);
  color: var(--text-secondary);
  border: 2px solid var(--border-color);
  border-radius: var(--radius-sm);
  font-weight: 500;
  transition: all 0.2s ease;
}

.layout-button:hover {
  background-color: var(--bg-tertiary);
  border-color: var(--primary-color);
  transform: translateY(-1px);
  box-shadow: var(--shadow-md);
}

.layout-button.active {
  background-color: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

/* 主内容区域 */
.main-content {
  display: flex;
  gap: 24px;
  width: 100%;
  flex-wrap: wrap;
  flex-direction: row;
}

/* 垂直布局时的样式 */
.main-content.vertical {
  flex-direction: column;
}

.editor-section,
.preview-section {
  flex: 1;
  min-width: 300px;
}

/* 模板列表部分 */
.template-list-section {
  width: 100%;
}

/* 确保组件有适当的样式 */
.editor-section .component,
.preview-section .component,
.template-list-section .component {
  background-color: var(--bg-primary);
  border-radius: var(--radius-lg);
  padding: 20px;
  box-shadow: var(--shadow-md);
  height: 100%;
  min-height: 400px;
}

/* 为编辑器和预览面板设置固定高度，确保它们在水平布局时高度一致 */
.editor-section .component {
  min-height: 500px;
}

.preview-section .component {
  min-height: 500px;
  display: flex;
  flex-direction: column;
}

/* 确保预览内容区域可以滚动 */
.preview-section .preview-content {
  flex: 1;
  overflow: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }
  
  .header {
    flex-direction: column;
    align-items: stretch;
  }
  
  h1 {
    text-align: center;
  }
  
  .layout-controls {
    justify-content: center;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content-container.horizontal {
    flex-direction: column;
  }
  
  .header {
    flex-direction: column;
    align-items: stretch;
  }
  
  h1 {
    text-align: center;
  }
  
  .layout-controls {
    justify-content: center;
  }
}
</style>